<?php

define('access',1);

class SRJG {

    const DBPATH = '/usr/local/etc/jukebox.db';
    const JFOLDER = '/usr/local/etc/www/Jukebox/';
    const RECENT_MAX = '200';
    const EXCLUDE = "/\b(sample|cd2|part2)\b/i";
    const LOG = '/usr/local/etc/imbd_db';
    const COMM = '/usr/local/etc/imbd_comm';

    var $path;
    var $Cnfg;
    var $BrsFld;
    var $db;
    var $Movies_Path;
    var $Jukebox_Size;
    var $ischanged;
    var $item_pos;
    var $category_title;
    var $mode;
    var $script_url;

    function __construct($mode = NULL, $CategoryTitle = NULL, $Jukebox_Size = NULL, $Item_Pos = NULL) {
        $this->script_url = 'http://127.0.0.1' . $_SERVER["SCRIPT_NAME"];
        $this->Jukebox_Size = $Jukebox_Size;
        $this->mode = $mode;
        $this->category_title = $CategoryTitle;
        $this->item_pos =  isset($Item_Pos) ? $Item_Pos : "0";
        /*if (!$Item_Pos) {
            $this->item_pos = "0";
        } else {
            $this->item_pos = $Item_Pos;
        } */
        if (!file_exists(self::DBPATH)) {
            $this->db = new SQLite3(self::DBPATH);
            $this->db->exec("CREATE TABLE settings (ID TEXT UNIQUE, key TEXT, value TEXT)");
            $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_size', '34');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('font_offset', '-3.5');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('font_shadow_color', '0:0:0');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('font_type', '/usr/local/bin/Resource/font/arialnarrowbold.ttf');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('font_color', '255:255:255');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('sub_language', 'ro');"
                    . "INSERT OR REPLACE INTO settings (key, value) VALUES ('jukebox_size', '2x6')");
            $this->db->exec("CREATE TABLE t1 (Movie_ID INTEGER PRIMARY KEY AUTOINCREMENT,imdbid TEXT, genre TEXT, title TEXT, year TEXT, path TEXT, path2 TEXT, file TEXT, ext TEXT, watched TEXT, plot TEXT, rating TEXT, cast TEXT, director TEXT, runtime TEXT, writer TEXT, location TEXT, filetime TEXT, nfotime TEXT, dateStamp DATE DEFAULT CURRENT_DATE)");
            //$this->db->close();
        }
        $this->db = new SQLite3(self::DBPATH);
        $this->BrsFld = $CategoryTitle;
        if ($this->BrsFld === NULL) {
            $this->BrsFld = '/tmp/ramfs/volumes';
        }
        $this->Movies_Path = $this->read_config('moviefolder');
        if (!$Jukebox_Size) {
            $this->Jukebox_Size = $this->read_config('jukebox_size');
        }
        $this->ischanged = "0";
        switch ($this->mode) {
            case "WatcheUpDB": $this->WatcheUpDB();
                break;
            case "Update": $this->Update_rss();
                break;
            case "ReplaceCd1byCd2": $this->ReplaceCd1byCd2();
                break;
            case (preg_match("/BrsFld/", $mode) ? TRUE : FALSE) : $this->browse_folder();
                break;
            case (preg_match("/MenuCfg/", $mode) ? TRUE : FALSE) : $this->FBrowser();
                break;
            case (preg_match("/SvCfg/", $mode) ? TRUE : FALSE) : $this->SvCfg();
                break;
            case "setup": $this->setup();
                break;
            case "set_font_size": $this->set_font_size();
                break;
            case "set_font_offset": $this->set_font_offset();
                break;
            case "set_font_type": $this->set_font_type();
                break;
            case "browser": $this->file_browser();
                break;
            case "videorender": $this->video_renderer();
                break;
            case "srtxml": $this->srt_to_xml();
                break;
            case "network": $this->network();
                break;
            case "file_op": $this->file_op();
                break;
            case "add_fav": $this->add_fav();
                break;
            case "rem_fav": $this->rem_fav();
                break;
            case "sub_set_size": $this->sub_set_size();
                break;
            case "sub_sel": $this->sub_sel();
                break;
            case "sub_download": $this->sub_download();
                break;
            case "sub_encode": $this->sub_encode($this->category_title ? $this->category_title : NULL);
                break;
            case "info": $this->info();
                break;
            default : $this->rss_display();
                break;
        }
    }

    function read_config($data) {
        $this->db->exec("CREATE TABLE IF NOT EXISTS settings (ID TEXT UNIQUE, key TEXT, value TEXT)");
        $results = $this->db->query("SELECT value FROM settings WHERE key = '" . $data . "'");
        $read = $results->fetchArray();
        return $read['value'];
    }
    function set_font_size(){
        require 'srjg/set_font_size.php';
    }
    function set_font_offset(){
        require 'srjg/set_font_offset.php';
    }
    function set_font_type(){
        require 'srjg/set_font_type.php';
    }
    function sub_set_size(){
        require 'srjg/sub_set_size.php';
    }
    function sub_sel(){
        require 'srjg/sub_sel.php';
    }
    function sub_download(){
        require 'srjg/sub_download.php';
    }
    function info(){
        require 'srjg/info.php';
    }
    function setup() {
            switch ($this->category_title){
                case "font_size": $echo = ($this->read_config($this->category_title)) ? $this->read_config($this->category_title) : "34";
                    break;
                case "jukebox_size": $echo = ($this->read_config($this->category_title)) ? $this->read_config($this->category_title) : "2x6";
                    break;
                case "moviefolder": $echo = ($this->read_config($this->category_title)) ? $this->read_config($this->category_title) : "not set";                    @file_put_contents('/usr/local/etc/.moviefolder', $moviefolder);
                    break;
                default: $echo = ($this->read_config($this->category_title)) ? $this->read_config($this->category_title) : "not set";
                    break;
            }
            echo $echo;
        //$this->db->close();
    }
    
    function network(){
        
        
    }
    function file_op(){
        if ($this->category_title == "delete"){
            $file = urldecode($this->Jukebox_Size);
            $command = "rm -f -R '$file'";
            shell_exec($command);
            echo "done";
        }
        if ($this->category_title == "copy"){
            $command = "cp -f -R ".  str_replace(' ', '\ ', urldecode($this->Jukebox_Size))." ". str_replace(' ', '\ ', urldecode($this->item_pos));
            shell_exec($command);
            echo "done";
        }
    }
    
    function mount_network(){
        $ip = shell_exec("/tmp/usbmounts/sda3/nmblookup $value");
        preg_match_all("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $ip, $matches);
        shell_exec('/tmp/usbmounts/sda3/mount.cifs ');
    }
    
    function video_renderer(){
        require 'srjg/video_renderer.php';
    }
    
    function sub_encode($encode = NULL){
        if (!preg_match("/www\/cgi-bin\/scripts\/util/", $this->read_config('font_type'))){
            if(!$encode){
    $encoding = exec("/opt/bin/file -b --mime-encoding /tmp/pre_test.xml");
    if($encoding == "iso-8859-1" || preg_match("/unknown/", $encoding) || $encoding == "binary" ){
        $encoding = "iso-8859-2";
    }
            } else {
                $encoding = $encode;
            }
            if($encoding == "none"){
                exec("cp -f /tmp/pre_test.xml /tmp/test.xml");
            } else {
            exec("/opt/bin/iconv -f $encoding -t utf-8 /tmp/pre_test.xml > /tmp/test.xml"); }
    //exec("/opt/bin/recode l2..utf8 /tmp/test.xml");
}
    }
    function srt_to_xml($file_full = NULL){
        require 'srjg/srt_to_xml.php';
    }
    function add_fav(){
        $this->db->exec("CREATE TABLE IF NOT EXISTS favorites (ID TEXT UNIQUE, fav TEXT)");
        $this->db->exec("INSERT OR REPLACE INTO favorites (fav) VALUES ('".$this->category_title."')");
        echo "done";
    }
    function rem_fav(){
        $this->db->exec("DELETE FROM favorites WHERE fav = '".$this->category_title."'");
        echo "done";
    }

    function write_log($comm) {
        file_put_contents(SRJG::LOG, $comm);
    }

    function rss_display() {
        require 'srjg/rss_display.php';
    }

    function UpdateDB() {
        require 'srjg/update_db.php';
    }

    function GenerateMovieList() {
        require 'srjg/rebuild_db.php';
    }

    function Update() {
        $this->Headers();
        echo '
<onEnter>
showIdle();
postMessage("return");
</onEnter>
';
        $this->GenerateMovieList();
        echo '<channel>';
        $this->Footer();
    }

    function WatcheUpDB($movie = NULL, $watch = NULL) {
        if(!$watch){
        $watch = $this->Jukebox_Size;}
        if(!$movie){
            $movie = $this->category_title;
        }
        $parts = pathinfo($movie);
        $dirfile = $parts['dirname'];
        if($watch == "2" || $watch == "1"){
            if(file_exists($dirfile. '/.watched') && $watch == "1"){
                @unlink($dirfile . '/.watched');
                $this->db->exec("UPDATE t1 set Watched = 'NULL' WHERE path2 like '".$this->db->escapeString($dirfile)."'");
            } else {
                @file_put_contents($dirfile . '/.watched', "1");
                $this->db->exec("UPDATE t1 set Watched = '1' WHERE path2 like '".$this->db->escapeString($dirfile)."'");
            }
        }
    }

    function Headers() {
        echo '<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<bookmark>Jukebox</bookmark>
';
    }

    function Footer() {
        echo '</channel>
</rss>
';
    }

    function UpdateMenu() {
        require 'srjg/update_menu.php';
    }

    function prepare_items() {
        switch ($this->mode) {
            case "genre":
                if ($this->category_title === 'AllMovies') {
                    $sql = "SELECT * FROM t1 ORDER BY title COLLATE NOCASE";
                } else {
                    $sql = "SELECT * FROM t1 WHERE genre LIKE '%$this->category_title%' ORDER BY title COLLATE NOCASE";
                };
                break;
            case "alpha":
                if ($this->category_title === "0-9") {
                    $sql = "SELECT * FROM t1 WHERE title LIKE '9%' OR title LIKE '8%' OR title LIKE '7%' OR title LIKE '6%' OR title LIKE '5%' OR title LIKE '4%' OR title LIKE '3%' OR title LIKE '2%' OR title LIKE '1%' OR title LIKE '0%'";
                } else {
                    $sql = "SELECT * FROM t1 WHERE title LIKE '$this->category_title%' ORDER BY title COLLATE NOCASE";
                };
                break;
            case "year": $sql = "SELECT * FROM t1 WHERE year LIKE '%$this->category_title%' ORDER BY title COLLATE NOCASE";
                break;
            case "recent": $sql = "SELECT * FROM t1 ORDER BY filetime DESC LIMIT '" . self::RECENT_MAX . "'";
                break;
            case "notwatched": $sql = "SELECT * FROM t1 WHERE watched <>'1' OR watched IS NULL ORDER BY filetime DESC";
                break;
            case "moviesearch": $sql = "SELECT * FROM t1 WHERE title LIKE '%$this->category_title%' ORDER BY title COLLATE NOCASE";
                break;
            case "yearSelection": $sql = "SELECT DISTINCT year FROM t1 ORDER BY year COLLATE NOCASE";
                break;
            case "genreSelection": $sql = 'SELECT group_concat(genre, " / ") genre FROM t1 ORDER BY title COLLATE NOCASE';
                break;
            case "alphaSelection": $sql = "SELECT DISTINCT substr(title, 1, 1) FROM t1 ORDER BY title COLLATE NOCASE";
                break;
        }
        $results = $this->db->query($sql);
        if (($this->mode == "genre") || ($this->mode == "alpha") || ($this->mode == "year") || ($this->mode == "recent") || ($this->mode == "notwatched") || ($this->mode == "moviesearch") || ($this->mode == "yearSelection")) {
            while ($row = $results->fetchArray()) {
                $rss .= $this->display_items($row);
            }
            return $rss;
        } else if ($this->mode == "genreSelection") {
            $rss = "";
            while ($row = $results->fetchArray()) {
                $row = array_unique($row);
                $row = explode(" / ", $row[0]);
                $row = array_unique($row);
                foreach ($row as $row) {
                    $rss .= '
			<item>
			<title>' . $row . '</title>
			<path>' . SRJG::JFOLDER . 'images/genre</path>
			<file>' . $row . '</file>
			</item>';
                }
            }
            return $rss;
        } else if ($this->mode == "alphaSelection") {
            $rss = NULL;
            $iteration = "0";
            while ($row = $results->fetchArray()) {
                if ($iteration == "0") {
                    if (is_numeric($row[0])) {
                        $iteration = "1";
                        $rss = '<item>
                                 <title>0-9</title>
                                 <path>' . SRJG::JFOLDER . 'images/alpha</path>
                                 <file>JukeMenu_Number</file>
                                 </item>';
                    }
                } else {
                    $rss .= $this->display_items($row);
                }
            }
            return $rss;
        }
    }

    function display_items($row) {
        $rss = '
    <item>
    ';
        if (($this->mode == "genre") || ($this->mode == "alpha") || ($this->mode == "year") || ($this->mode == "recent") || ($this->mode == "notwatched") || ($this->mode == "moviesearch")) {
            $rss .= '<title>' . $row["title"] . '</title>
	<IdMovie>' . $row["Movie_ID"] . '</IdMovie>
	<path>' . htmlspecialchars($row["path2"]) . '</path>
        <full_path>' . htmlspecialchars($row["path"]) . '</full_path>
	<file>' . htmlspecialchars($row["file"]) . '</file>
	<ext>' . $row["ext"] . '</ext>
	<Watched>' . $row["watched"] . '</Watched>
	<plot>' . $row["plot"] . '</plot>
	<year>' . $row["year"] . '</year>
	<genre>' . $row["genre"] . '</genre>
	<director>' . $row["director"] . '</director>
	<writer>' . $row["writer"] . '</writer>
	<location>' . $row["location"] . '</location>
	<cast>' . $row["cast"] . '</cast>
	<rating>' . $row["rating"] . '</rating>
	<runtime>' . $row["runtime"] . '</runtime>';
        } else if ($this->mode == "yearSelection") {
            $rss .= '<title>' . $row["year"] . '</title>';
        } else if ($this->mode == "genreSelection") {
            $row = array_unique($row);
            $row = explode(" / ", $row[0]);
            $row = array_unique($row);
            foreach ($row as $row) {
                $rss .= '
			<title>' . $row . '</title>
			<path>' . SRJG::JFOLDER . 'images/genre</path>
			<file>' . $row . '</file>';
            }
        } else if ($this->mode == "alphaSelection") {
            $rss .= '
	<title>' . $row[0] . '</title>
	<path>' . SRJG::JFOLDER . 'images/alpha</path>
	<file>JukeMenu_' . $row[0] . '</file>';
        }

        $rss .= '
    </item>';
        return $rss;
    }

    function ReplaceCd1byCd2() {
        $Cd2 = $this->category_title;
        echo '<?xml version="1.0" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<onEnter>
setEnv("MovieCd2","' . $Cd2 . '");
showIdle();
postMessage("return");
</onEnter>
<mediaDisplay name="nullView"/>
<channel></channel></rss>';
    }

    function FBrowser() {
        require 'srjg/fbrowser.php';
    }

    function browse_folder() {
        require 'srjg/browse_folder.php';
    }

    function SvCfg() {
        $this->Headers();
        echo '
	<onExit>
	redrawDisplay();
	</onExit>
	<channel>';
        $this->db->exec("CREATE TABLE IF NOT EXISTS settings (ID TEXT UNIQUE, key TEXT, value TEXT)");
        switch ($this->category_title){
            case "jukebox_size": ($this->read_config('jukebox_size')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'jukebox_size'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('jukebox_size', '$this->Jukebox_Size') ");
                break;
            case "moviefolder": ($this->read_config('moviefolder')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'moviefolder'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('moviefolder', '$this->Jukebox_Size') ");
                break;
            case "font_size" : ($this->read_config('font_size')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'font_size'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_size', '$this->Jukebox_Size') ");
                break;
            case "font_offset" : ($this->read_config('font_offset')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'font_offset'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_offset', '$this->Jukebox_Size') ");
                break;
            case "font_type" : ($this->read_config('font_type')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'font_type'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_type', '$this->Jukebox_Size') ");
                break;
            case "font_color" : ($this->read_config('font_color')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'font_color'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_color', '$this->Jukebox_Size') ");
                break;
            case "font_shadow_color" : ($this->read_config('font_shadow_color')) ? $this->db->exec("UPDATE settings SET value = '$this->Jukebox_Size' WHERE key = 'font_shadow_color'") : $this->db->exec("INSERT OR REPLACE INTO settings (key, value) VALUES ('font_shadow_color', '$this->Jukebox_Size') ");
                break;
            default: 
                break;
        }
        $this->db->close();
        $this->Footer();
    }

    function Update_rss() {
        require 'srjg/update_rss.php';
    }

    function file_browser($arg1 = null, $arg2 = null, $arg3 = null, $arg4=null) {
        require 'srjg/file_browser.php';
    }

}

class LANG extends SRJG {

    const alpha = "Alphabet";
    const genre = "Genre";
    const recent = "Recently Added";
    const select = "Select Movies by:";
    const update = "Update Jukebox";
    const notwatched = "Not Watched";
    const year = "Year";
    const search = "Search";
    const config = "Config";
    const jukeboxtop = "1 = Switch View | 2 = Mark as Watched | Enter = Select | Rtn = Previous Menu/View | Play = Play Video/Movie";
    const updatefast = "Fast";
    const updaterebuild = "Rebuild";
    const cfglang = "Language";
    const cfgjukebox_size = "View";
    const cfgmovies_path = "Movie path";
    const cfgmovie_filter = "Filter";
    const cfgsingledb = "Single Database";
    const cfgrecent_max = "Max recent movie";
    const cfgimdb = "Use Imdb";
    const cfgjukebox_path = "Jukebox path";
    const cfgport = "Port";
    const cfgversion = "Version";
    const cfgyes = "Yes";
    const cfgno = "No";
    const fbrowser_title = "Movies Path:";
    const fbrowser_valid = "to validate";

}

$query = $_SERVER["QUERY_STRING"];
if ($query) {
    $queryArr = explode(',', $query);
}
new SRJG($queryArr[0], urldecode($queryArr[1]), $queryArr[2], $queryArr[3]);
?>